using System.Threading.Tasks;
using Abp.Configuration;
using Abp.Zero.Configuration;
using FwProject.Authorization.Accounts.Dto;
using FwProject.Authorization.Users;
using FwProject.Manager;
using Abp;
using Abp.ObjectMapping;
using FwProject.Core.Restaurant;
using Abp.Authorization;
using System;
using Abp.Domain.Repositories;
using FwProject.Users;
using FwProject.Restaurant.Dto;
using Abp.UI;
using FwProject.Comm;
using System.Linq;
using Microsoft.AspNetCore.Identity;

namespace FwProject.Authorization.Accounts
{
   
    public class AccountAppService : FwProjectAppServiceBase, IAccountAppService
    {
        private readonly UserRegistrationManager _userRegistrationManager;
        private readonly IRepository<User, long> _userRepository;
        private readonly CarInfoManager _carInfoManager;
        private readonly IUserAppService _iuserAppService;
        private readonly RestaurantInfoManager _restaurantInfoManager;
        private readonly RestaurantUserManager _restaurantUserManager;
        private readonly UserManager _userManager;
        private readonly IPasswordHasher<User> _passwordHasher;
        public IObjectMapper _map { get; set; }
        public IGuidGenerator _guid { get; set; }
        public AccountAppService(
            UserRegistrationManager userRegistrationManager,CarInfoManager carInfoManager,
            RestaurantInfoManager restaurantInfoManager,
             IRepository<User, long> userRepository,
             IUserAppService iuserAppService, RestaurantUserManager restaurantUserManager,
              UserManager userManager,
              IPasswordHasher<User> passwordHasher
            )
        {
            _passwordHasher = passwordHasher;
             _iuserAppService = iuserAppService;
            _userRepository =userRepository; ;
            _userRegistrationManager = userRegistrationManager;
            _carInfoManager=carInfoManager;
            _restaurantInfoManager = restaurantInfoManager;
            _map = NullObjectMapper.Instance;
            _restaurantUserManager = restaurantUserManager;
            _userManager = userManager;


        }

        public async Task<IsTenantAvailableOutput> IsTenantAvailable(IsTenantAvailableInput input)
        {
            var tenant = await TenantManager.FindByTenancyNameAsync(input.TenancyName);
            if (tenant == null)
            {
                return new IsTenantAvailableOutput(TenantAvailabilityState.NotFound);
            }

            if (!tenant.IsActive)
            {
                return new IsTenantAvailableOutput(TenantAvailabilityState.InActive);
            }

            return new IsTenantAvailableOutput(TenantAvailabilityState.Available, tenant.Id);
        }


        #region app 用户注册
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns>The register.</returns>
        /// <param name="input">Input.</param>
        public async Task<RegisterOutput> Register(RegisterInput input)
        {
             Guid? factoryid = null;
            long driverID = 0;
            if (input.Mobile.Length!=11)
                throw new UserFriendlyException("手机号码位数有误");

            var userModel = _userRepository.GetAll().Where(o => o.Mobile == input.Mobile).FirstOrDefault();
            if(userModel!=null)
                throw new UserFriendlyException("手机号码已注册过");



            if (!string.IsNullOrEmpty(input.DriverPhoneNumber))
            {
                if (input.DriverPhoneNumber.Length != 11)
                    throw new UserFriendlyException("配送司机手机号码位数有误");

                ///一定要上传车牌号  通过车牌号码查询出工厂信息 和司机编号
                var model = _userRepository.GetAll().Where(o => o.Mobile == input.DriverPhoneNumber).FirstOrDefault();  //await _iuserAppService.GetUserByMobile(input.DriverPhoneNumber);

                if (model == null)
                    throw new UserFriendlyException("配送司机手机错误");

                if (model.EmployeeType != EmployeeType.司机类型)
                    throw new UserFriendlyException("请输入正确的司机电话");

                //得到司机编号
                 driverID = model.Id;///司机id
                ///得到汽车信息
                factoryid = _userRepository.Get(model.Id).FactoryinfoId.Value;
            }
         

            var user = await _userRegistrationManager.RegisterAsync(
                input.Name,
                input.Surname,
                $"{DateTime.Now.ToString("yyyyMMddhhmmss")}@123.com",
                input.Mobile,
                input.Password,
                input.Mobile,
                factoryid,
                true // Assumed email address is always confirmed. Change this if you want to implement email confirmation.
            );

            if (factoryid.HasValue) {
                input.RestaurantDto.EmployeeDriverid = driverID;
                input.RestaurantDto.FactoryinfoId = factoryid;
                var rmodel = _map.Map<RestaurantInfo>(input.RestaurantDto);
                rmodel.Id = _guid.Create();
                rmodel.RestaurantContact = user.Name;
                rmodel.Mobile = user.Mobile;
                ///创建一个餐厅
                await _restaurantInfoManager.CreateRestaurant(rmodel);
                var restaurantUserModelInput = new RestaurantUserInput();
                restaurantUserModelInput.EmployeeRestaurantId = user.Id;
                restaurantUserModelInput.RestaurantInfoId = rmodel.Id;
                var restaurantUserModel = _map.Map<RestaurantUserInfo>(restaurantUserModelInput);
                restaurantUserModel.Id = _guid.Create();
                await _restaurantUserManager.CreateRestaurantUser(restaurantUserModel);
            }

            var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);

            return new RegisterOutput
            {
                CanLogin = user.IsActive && (user.IsEmailConfirmed || !isEmailConfirmationRequiredForLogin)
            };
        }
        #endregion
        #region app 修改用户密码

        public void EditRestPassword(string Mobile,string newPassword) {



             var user=  _userRepository.GetAll().Where(o => o.Mobile == Mobile).FirstOrDefault();
             UserManager.ResetPasswordAsync(user, Mobile, newPassword);
             if (user == null)
                throw new UserFriendlyException("手机号码不存在");
              user.Password = _passwordHasher.HashPassword(user, newPassword);
         
        }
        #endregion
        public void EditRestTokenPassword(string Mobile,string token, string newPassword) {

            var user = _userRepository.GetAll().Where(o => o.Mobile == Mobile).FirstOrDefault();
            if (user == null)
                throw new UserFriendlyException("手机号码不存在");

            UserManager.ResetPasswordAsync(user, token, newPassword);
        }

        public void EditPassword(long id, string newPassword)
        {
            var user = _userRepository.GetAll().Where(o => o.Id == id).FirstOrDefault();
            UserManager.ResetPasswordAsync(user,"",newPassword);
            user.Password = _passwordHasher.HashPassword(user, newPassword);

        }
    }
}
